<?php
	session_unset();
	session_start();
	require_once('../inc/fnc.php');
	require_once('../inc/conn.php');
	require_once('../inc/settings.php');

	
	// Initializing variables
	$email = $_POST['email'];
	$pwd = sha1($_POST['pwd']);
	$time = time();
	
	// Authorizing user
	$query = "SELECT * FROM `users` "; 
	$query .= " WHERE pwd = '" . $pwd . "' "; 
	$query .= " AND email = '" . $email . "' ";
	$query .= " AND `delete flag` = 'N' LIMIT 1";
	
	$result = mysql_query( $query, $connection);
	
	//If user is authenticated, log user in
	if (mysql_num_rows($result) == 1) {
		$query1 = mysql_query("SELECT * FROM `users` WHERE pwd = '" . $pwd . "' AND email = '" . $email . "' AND `delete flag` = 'N' AND `email varification` = 'Y' LIMIT 1");
		if (mysql_num_rows($query1) == 1) {
			$_SESSION['login'] = TRUE;
			
			while($row = mysql_fetch_array($result)){
				$_SESSION['user'] = $row['usrname'];
				$_SESSION['userId'] = $row['userid'];
			}
			
			//If the user has checked 'Remember Me', then set cookie to remmber user
			if(isset($_POST['rem']) && $_POST['rem'] == 'Yes'){
				
				$uid = $_SESSION['userId'];
				$identifier = genRandomString(45);
				$token = genRandomString(45);
				
				if(insertCookie($uid, $identifier, $token)) {	
					setcookie('uid', $_SESSION['userId'], time()+60*60*24*30, "/");			//Cookie Expiration time set to 1 month from now
					setcookie('identifier', $identifier, time()+60*60*24*30, "/");
					setcookie('token', $token, time()+60*60*24*30, "/" );
				} else {
					//Setting remember me failed
				}
				
			}
			
			// Redirecting to home page
			$url = $_SERVER['HTTP_REFERER'];
			$url = explode("?",$url);
			$url = $url[0];
			
			if(isset($_SESSION['redirecturl'])){
				$url = $_SESSION['redirecturl'];
				unset($_SESSION['redirecturl']);
			} else {
				$url = DOMAIN;
			}
			$error['type'] = 'redirect';
			
				
			
			$error['url'] = $url;
			echo json_encode($error);
			//redirect_to($url);
		} else{
			//$_SESSION['login'] = 3;
			$error['type'] = 'unverified';
			echo json_encode($error);
		}
		
	} else { 
		//$_SESSION['login'] = 2; 
		$error['type'] = 'invalid';
		echo json_encode($error);
	} 

	
?>